layui.define(['jquery', 'popup', 'loading'], function (exports) {
    var $ = layui.jquery,
        popup = layui.popup,
        loading = layui.loading;

    var commonAjax = {
        send: function (url, obj, success) {
            buildRequest(url, obj);
            dealFail(obj);

            // 请求成功
            obj.success = function (r) {
                if (r.code === 200) {
                    success(r) && (success)();
                } else if (r.code === 401) {
                    popup.success('登录已失效，请重新登录', function () {
                        layui.data('dimples', {
                            remove: true
                        })
                        parent.location.href = getRootPath() + '/login.html';
                    });
                } else if (r.code === 402) {
                    popup.success(r.msg, function () {
                        layui.data('dimples', {
                            remove: true
                        })
                        parent.location.href = getRootPath() + "/login.html";
                    })
                } else if (r.code === 403) {
                    popup.warning('对不起，您暂无该操作权限', function () {
                        parent.location.href = getRootPath() + '/error/403.html';
                    });
                } else if (r.code === 500) {
                    popup.failure(r.msg ? r.msg : '操作失败');
                    console.error(r);
                } else {
                    popup.failure(r.msg ? r.msg : '操作失败');
                    console.error(r);
                }
                loading.loadRemove();
            }
            $.ajax(obj);
        },

        get: function (url, obj, success, error) {
            buildRequest(url, obj);
            dealFail(obj);

            // 请求成功
            obj.success = function (r) {
                if (r.code === 200) {
                    success(r) && (success)();
                } else if (r.code === 401) {
                    popup.success('登录已失效，请重新登录', function () {
                        layui.data('dimples', {
                            remove: true
                        })
                        location.href = getRootPath() + '/login.html';
                    });
                } else if (r.code === 402) {
                    popup.success(r.msg, function () {
                        layui.data('dimples', {
                            remove: true
                        })
                        location.href = getRootPath() + "/login.html";
                    })
                } else if (r.code === 403) {
                    popup.warning('对不起，您暂无该操作权限', function () {
                        location.href = getRootPath() + '/view/error/403.html';
                    });
                } else if (r.code === 500) {
                    error(r) && (error)();
                } else {
                    error(r) && (error)();
                }
                loading.loadRemove();
            }
            $.ajax(obj);
        },

        img: function (url, success) {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', BASE_URL + url, true);
            xhr.responseType = "blob";
            xhr.setRequestHeader("Authorization", "Bearer " + layui.data("dimples").token);
            xhr.onload = function () {
                if (this.status == 200) {
                    var blob = this.response;
                    success(blob) && (success)();
                }
            }
            xhr.send();
        },

        download: function (url, params, fileName) {
            // self.view.loadBar.start();
            url += '?' + parseParams(params);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', BASE_URL + url, true);
            xhr.responseType = "blob";
            xhr.onload = function () {
                if (this.status === 200) {
                    // self.view.loadBar.finish();
                    var fileType = this.response.type;
                    var blob = this.response;
                    var reader = new FileReader();
                    reader.readAsDataURL(blob);
                    reader.onload = function (e) {
                        if ('msSaveOrOpenBlob' in navigator) { // IE，Edge
                            var base64file = e.target.result + '';
                            window.navigator.msSaveOrOpenBlob(createFile(base64file.replace('data:' + fileType + ';base64,', ''), fileType), fileName);
                        } else { // chrome，firefox
                            var link = document.createElement('a');
                            link.download = fileName;
                            link.style.display = "none";
                            var blobs = new Blob([blob]);
                            if (blobs.size === 0) {
                                layer.msg('下载失败，文件内容为空！');
                            } else {
                                link.href = URL.createObjectURL(blobs);
                                document.body.appendChild(link);
                                link.click();
                                document.body.removeChild(link);
                            }
                        }
                    }
                } else {
                    // self.view.loadBar.error();
                    popup.failure('下载失败');
                }
            };
            xhr.send();
        }
    };


    function buildRequest(url, obj) {
        if (url) {
            if (url.includes(BASE_URL)) {
                obj.url = url;
            } else {
                obj.url = BASE_URL + url;
            }
        }
        // 配置请求头
        if (!obj.headers) {
            obj.headers = {　　　　　　　　　　// 兼容IE9
                'cache-control': 'no-cache',
                'Pragma': 'no-cache',
                'Authorization': layui.data("dimples").token,
                'X-Requested-With': 'XMLHttpRequest'
            };
        }
        // 请求方式
        if (!obj.type) obj.type = "GET";
        // 请求类型
        if (!obj.dataType) obj.dataType = "json";
        // 配置为false时，表示不从浏览器缓存中获取数据，调试时可以看到，发Get请求时，会自动加上时间戳
        if (!obj.cache) obj.cache = false;
        // 是否异步
        if (!obj.async) obj.async = true;
        obj.crossDomain = true === !(document.all);//这句是关键

        if (obj.type != "GET" || obj.type != "get") {
            if (obj.processData == false && obj.contentType == false) {
                obj.processData = false;
                obj.contentType = false;
            } else {
                obj.dataType = "json";
                obj.contentType = "application/json";
            }
        }
    }

    function dealFail(obj) {
        // 请求失败
        if (!obj.error) {
            obj.error = function (err) {
                loading.loadRemove();
                popup.failure('网络连接失败!');
                console.log("网络连接失败" + err);
                console.log("请求URL: " + obj.url);
            }
        }
    }

    function parseParams(param, key, encode) {
        if (param == null) return '';
        let arr = [];
        let t = typeof (param);
        if (t === 'string' || t === 'number' || t === 'boolean') {
            arr.push(key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param));
        } else {
            for (let i in param) {
                let k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
                arr.push(parseParams(param[i], k, encode));
            }
        }
        return arr.join("&");
    }

    // 解析 BASE64文件内容 for IE，Edge
    function createFile(urlData, fileType) {
        let bytes = window.atob(urlData),
            n = bytes.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bytes.charCodeAt(n);
        }
        return new Blob([u8arr], {type: fileType});
    }

    //输出接口
    exports('ajax', commonAjax); // 使用的模块名称
});